<template>
  <div class="robot-editor">
    <div class="robot-e-title bottom-line mask pd10 flex flex-vcenter">
      <h2 class="pr10">机体列表</h2>
      <div class="pl10">
        <form action @submit="search" class="flex flex-vcenter">
          <input type="text" v-model="searchValue" placeholder="搜索机体名" />
          <Button type="primary" size="large">
            <i class="iconfont icon-LC_icon_search_line_2"></i>
          </Button>
        </form>
      </div>
      <div class="operate pl10">
        <Button type="primary" @click="changeRobotList(page - 1)">上一页</Button>
        <span class="pl10 pr10">{{ page }} / {{ totalPage }}</span>
        <Button type="primary" @click="changeRobotList(page + 1)">下一页</Button>
        <Button type="primary" size="large" title="新增">
          <i class="iconfont icon-add"></i>
        </Button>
        <Button type="primary" size="large" title="上传缩略图">
          <i class="iconfont icon-save"></i>
        </Button>
        <Button type="primary" size="large" title="上传大图">
          <i class="iconfont icon-save"></i>
        </Button>
      </div>
    </div>
    <div class="robot-pannel mask">
      <ScrollView>
        <div class="robot-list flex flex-wrap">
          <RobotItem
            v-for="item in robots"
            :key="item.id"
            :data="item"
            @changeWeapon="changeWeapon"
            @changeExchange="changeExchange"
            @changeBigSprite="changeBigSprite"
            @changeSprite="changeSprite"
          />
        </div>
      </ScrollView>

      <FSMask v-show="isWeaponEditing">
        <div class="wp-list mask pd10">
          <div class="bar flex flex-vcenter flex-hcenter">
            <input type="text" placeholder="搜索武器名" v-model="searchWeapon" />
            <Button type="primary" size="large">
              <i class="iconfont icon-LC_icon_search_line_2"></i>
            </Button>
            <Button type="primary" size="large" @click="hideWeaponList">X</Button>
          </div>
          <div class="list-content">
            <div class="has-weapon flex flex-wrap flex-hcenter bottom-line">
              <WeaponListItem
                v-for="item in editingRobot.weaponList"
                :key="item.id"
                :data="item"
                @select="removeWeapon"
              />
            </div>
            <div class="ex-weapon flex flex-wrap flex-hcenter">
              <WeaponListItem
                v-for="item in weaponTmep"
                :key="item.id"
                :data="item"
                @select="addWeapon"
              />
            </div>
          </div>
        </div>
      </FSMask>
      <FSMask v-show="isExChangeEditing">
        <div class="rb-list mask pb10">
          <div class="bar flex flex-vcenter flex-hcenter">
            <input type="text" placeholder="搜索机体名" v-model="searchRobot" />
            <Button type="primary" size="large">
              <i class="iconfont icon-LC_icon_search_line_2"></i>
            </Button>
            <Button type="primary" size="large" @click="hideRobotsList">X</Button>
          </div>
          <div class="rb-list-content has-ex flex">
            <RobotListItem
              v-for="item in editingRobot.exchangeList"
              :key="item.id"
              :data="item"
              @select="removeRobots"
            />
          </div>
          <div class="rb-list-content flex flex-wrap">
            <RobotListItem
              v-for="item in robotTemp"
              :key="item.id"
              :data="item"
              @select="addRobots"
            />
            <div style="height:200px"></div>
          </div>
        </div>
      </FSMask>
    </div>
    <RobotSpriteList v-if="robotBigSprites.length" ref="bigSpriteList" :data="robotBigSprites" @select="changeBigSpriteAction"/>
    <RobotSpriteList v-if="robotSprites.length" ref="spriteList" :data="robotSprites" @select="changeSpriteAction"/>
  </div>
</template>
    
<script>
import ScrollView from '../../components/common/ScrollView.vue'
import Button from '../../components/common/Button.vue'
import FSMask from '../../components/common/FSMask.vue'
import RobotItem from '../../components/manager/robot/RobotItem.vue'
import WeaponListItem from '../../components/manager/weapon/WeaponListItem.vue'
import RobotListItem from '../../components/manager/robot/RobotListItem.vue'
import RobotSpriteList from '../../components/manager/robot/RobotSpriteList.vue'
import { nextTick, onMounted, reactive, ref, toRefs, watch } from 'vue'
import axios from '../../lib/request.js'
export default {
  components: { ScrollView, RobotItem, Button, FSMask, WeaponListItem, RobotListItem , RobotSpriteList},
  setup() {
    const state = reactive({
      page: 1, size: 21, total: 0, totalPage: 1, searchValue: '',
      robots: [],
      isWeaponEditing: false,
      isExChangeEditing: false,
      searchWeapon: '',
      searchRobot: '',
      weapons: [],
      weaponTmep: [],
      allRobots: [],
      robotTemp: [],
      editingRobot: {},
      robotSprites:[],
      robotBigSprites:[]
    })
    const bigSpriteList = ref()
    const spriteList = ref()

    onMounted(async () => {
      await getAllSprites()
      await getAllWeapon()
      await getAllRobots()
      await getRobotsByPage()
    })

    async function getRobotsByPage() {
      const { data } = await axios.get('/robots/getRobotsListByPage', { params: { page: state.page, size: state.size, search: state.searchValue } })
      data.data.forEach(e => {
        e.weaponList = state.weapons.filter(wp => e.weapons.includes(wp.id))
        e.exchangeList = data.data.filter(rb => e.exchange.includes(rb.id))
      })
      state.robots = data.data
      state.total = data.total
      state.totalPage = Math.ceil(state.total / state.size)
    }

    const changeRobotList = (num) => {
      if (num <= 0 || num > state.totalPage) return
      state.page = num
      getRobotsByPage()
    }

    const search = (event) => {
      event.stopPropagation()
      state.page = 1
      getRobotsByPage()
    }
    const getAllWeapon = async () => {
      const { data } = await axios.get('/weapon/getWeaponsByPage', { params: { size: 9999, page: 1 } })
      state.weapons = data.data
      state.weaponTmep = data.data
    }

    const getAllRobots = async () => {
      const { data } = await axios.get('/robots/getRobotsListByPage', { params: { page: 1, size: 9999 } })

      state.allRobots = data.data
      state.robotTemp = data.data
    }

    const getAllSprites = async ()=>{
      const sprites = await axios.get('/robots/getSprites')
      const bigSprites = await axios.get('/robots/getBigSprites')
      state.robotBigSprites = bigSprites.data.data
      state.robotSprites = sprites.data.data
      console.log(state);
    }

    watch(() => state.searchWeapon, (val, pre) => {
      const temp = state.weapons.filter(e => e.name.includes(state.searchWeapon))
      for (let i = temp.length - 1; i >= 0; i--) {
        state.editingRobot.weaponList.forEach(e => {
          e.id == temp[i].id && temp.splice(i, 1)
        })
      }
      state.weaponTmep = temp
    })

    watch(() => state.searchRobot, () => {
      const temp = state.allRobots.filter(e => e.name.includes(state.searchRobot))
      for (let i = temp.length - 1; i >= 0; i--) {
        state.editingRobot.exchangeList.forEach(e => {
          e.id == temp[i].id && temp.splice(i, 1)
        })
      }
      const idx = temp.findIndex(e => e.id === state.editingRobot.id)
      temp.splice(idx, 1)
      state.robotTemp = temp
    })

    const changeWeapon = (robot) => {
      state.editingRobot = robot
      state.isWeaponEditing = true
      const temp = state.weapons.slice(0)
      for (let i = temp.length - 1; i >= 0; i--) {
        state.editingRobot.weaponList.forEach(e => {
          e.id == temp[i].id && temp.splice(i, 1)
        })
      }
      state.weaponTmep = temp
    }

    const changeExchange = (robot) => {
      state.editingRobot = robot
      state.isExChangeEditing = true
      const temp = state.allRobots.slice(0)
      for (let i = temp.length - 1; i >= 0; i--) {
        state.editingRobot.exchangeList.forEach(e => {
          e.id == temp[i].id && temp.splice(i, 1)
        })
      }
      const idx = temp.findIndex(e => e.id === state.editingRobot.id)
      temp.splice(idx, 1)
      state.robotTemp = temp
    }

    const addWeapon = (wp) => {
      state.editingRobot.weaponList.push(wp)
      state.editingRobot.weapons.push(wp.id)
      const idx = state.weaponTmep.findIndex(e => e.id == wp.id)
      state.weaponTmep.splice(idx, 1)
    }
    const removeWeapon = (wp) => {
      const index = state.editingRobot.weaponList.findIndex(e => e.id == wp.id)
      const target = state.editingRobot.weaponList.splice(index, 1)
      const idIndex = state.editingRobot.weapons.findIndex(e => e == wp.id)
      state.editingRobot.weapons.splice(idIndex, 1)
      state.weaponTmep.push(target)
    }

    const hideWeaponList = () => {
      state.isWeaponEditing = false
      state.searchWeapon = ''
      state.editingRobot = {}
    }

    const hideRobotsList = () => {
      state.isExChangeEditing = false
      state.editingRobot = {}
    }

    const addRobots = (rb) => {
      state.editingRobot.exchangeList.push(rb)
      state.editingRobot.exchange.push(rb.id)
      const idx = state.robotTemp.findIndex(e => e.id == rb.id)
      state.robotTemp.splice(idx, 1)
      syncExchangeData(state.editingRobot)
    }
    const removeRobots = (rb) => {
      const index = state.editingRobot.exchangeList.findIndex(e => e.id == rb.id)
      // console.log(index);
      // debugger
      const target = state.editingRobot.exchangeList.splice(index, 1)[0]
      const idIndex = state.editingRobot.exchange.findIndex(e => e == rb.id)
      state.editingRobot.exchange.splice(idIndex, 1)
      state.robotTemp.push(target)
      console.log(target.id);
      syncExchangeData(state.editingRobot,target)
    }

    function syncExchangeData(rb,removeTarget) {
      rb.exchangeList.forEach((me, idx) => {
        state.robots.forEach((item) => {
          if (item.id == me.id) {
            const temp = [...rb.exchangeList, rb]
            temp.splice(idx, 1)
            item.exchangeList = temp
            item.exchange = item.exchangeList.map(e => e.id)
          }
        })
      })
      if(removeTarget){
        console.log(removeTarget,removeTarget.id);
        const target = state.robots.find(e=>e.id == removeTarget.id)
        console.log(target);
        target.exchange.length = 0
        target.exchangeList.length = 0
      }
      const rbs = state.robots.splice(0, state.robots.length)
      nextTick(() => {
        state.robots = rbs
      })
    }

    const changeBigSprite = (rb)=>{
      bigSpriteList.value.show()
      state.editingRobot = rb
    }

    const changeSprite = (rb)=>{
      spriteList.value.show()
      state.editingRobot = rb
    }

    const changeBigSpriteAction = (sp)=>{
      state.editingRobot.bigSprite = sp
    }

    const changeSpriteAction = (sp)=>{
      state.editingRobot.sprite = sp
    }
    return {
      bigSpriteList,spriteList,
      ...toRefs(state),
      changeRobotList,
      search,
      changeWeapon,
      removeWeapon, addWeapon, hideWeaponList, changeExchange, addRobots, removeRobots, hideRobotsList,changeBigSprite,changeSprite,
      changeBigSpriteAction,changeSpriteAction
    }
  }
}
</script>
<style lang="less" scoped>
.robot-editor {
  height: 100vh;
  .robot-e-title {
    height: 100px;
  }
  .robot-pannel {
    height: calc(100vh - 100px);

    /deep/ .view-pannel {
      width: 100%;
    }

    .robot-list {
      .robot-item {
        width: 32%;
        margin-right: 10px;
        margin-bottom: 10px;
        &:nth-child(3n) {
          margin-right: 0;
        }
      }
    }
  }
  .wp-list,
  .rb-list {
    width: 90vw;
    height: 90vh;
    background-color: rgba(0, 0, 0, 0.9);
    border-radius: 10px;
    .has-weapon,
    .has-ex {
      padding: 10px 0;
      margin-bottom: 10px;
    }
    .ex-weapon,
    .rb-list-content {
      // padding-bottom: 200px;
      overflow-x: hidden;
      overflow-y: auto;
      max-height: calc(90vh - 200px);
      .weapon-list-item {
        margin: 5px;
      }
    }
  }
}
</style>